/**
 * @author - cozevn.
 * @Date : 01-Dec-2011
 */
package vn.com.tiz.DocumentZ.view;

import java.util.ArrayList;

import vn.com.tiz.DocumentZ.R;
import vn.com.tiz.DocumentZ.utils.LogTools;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.Scroller;

public class DocumentView extends ViewGroup{

	String Content="Page 1";
	Paint mTextPaint;
	RectF rectBound;
	
	private Scroller mScroller;
	private float currentZoom = 1.0f;
	
	
	float lastX = 0;
	float xDistance = 0;
	int mMotionStartX = 0;
	int mMotionStartY = 0;

	private float mLastMotionX;
	private int mTouchSlop;
	private int mMaximumVelocity;
	private int mCurrentScreen;
	//private int mNextScreen = INVALID_SCREEN;

	
	private boolean mJustInterceptedAndIgnored = false;
	private boolean mMostlyScrollingInX = false;
	private boolean mMostlyScrollingInY = false;
	
	int DocumentHeight = 0;
	int DocumentWidth = 0;
	int CurrentWidth = 0;
	int CurrentHeight = 0;
	
	ArrayList<String> lines = new ArrayList<String>();
	
	float MinZoom = 0.5f;
	float MaxZoom = 2.0f;
	float CurrentZoom = 1.0f;
	
	private FrameLayout frameDocContainer;
	
	ImageViewZ img;
	
	int originLeft;
	int originWidth;
	
	boolean isFirstLayout = true;
	
	DocContainerView docContainer;
	
	public DocumentView(Context context){						
		super(context);
		
		//Window win context.getSystemService(Context.WINDOW_SERVICE);
		
		originWidth = 300;
		DocumentWidth = 400;
		DocumentHeight = 700;
		
		CurrentHeight = DocumentHeight;
		CurrentWidth = DocumentWidth;
		
		frameDocContainer = new FrameLayout(context);
		frameDocContainer.setBackgroundColor(Color.WHITE);
		
		//addView(frameDocContainer);
		
		docContainer = new DocContainerView(context);
		addView(docContainer);
		//originLeft = 
		//LayoutParams lp = new LayoutParams(300,LayoutParams.WRAP_CONTENT);		
		//setLayoutParams(lp);
		//originLeft = getLeft();
		
		mTextPaint = new Paint();
		mTextPaint.setAntiAlias(true);
		mTextPaint.setColor(Color.BLACK);
	
		
		setBackgroundColor(Color.CYAN);
		//Content = getContext().getResources().getString(R.string.sample);
		//rectBound = new  RectF(20,20,100,100);
		//lines.add("line 1");
		//lines.add("line 2");
		
		mScroller = new Scroller(context);
		
		img = new ImageViewZ(context);
		img.setBackgroundResource(R.drawable.video_thumb);
		img.setLocation(0,0);
		img.setSize(200, 300);
		
		docContainer.addView(img);
		//frameDocContainer.addView(img);
		
		
	}
		
	
	public void addComponent(BaseComponent component){
		
	}
	
	public float getCurrentZoom(){
		return currentZoom;
	}
	
	public void setZoom(float values){		
		currentZoom = values;
		zoom();
	}
	
	public void setZoomBy(float value){
		if(currentZoom + value <MinZoom){
			currentZoom = MinZoom;
		}
		if(currentZoom + value > MaxZoom){
			currentZoom = MaxZoom;
		}
		currentZoom += value;
		zoom();
	}
	
	private void zoom(){
		CurrentWidth = (int)(DocumentWidth*currentZoom);
		CurrentHeight = (int)(DocumentHeight*currentZoom);
		
		//setMeasuredDimension(newWidth, newHeight);
		//requestLayout();
//		
		//int centerX = 540/2;
		//int centerY = 960/2;
		
		//int l1 = originLeft;
		//int l2 = (int)(originLeft*currentZoom);
		
		//int newtop = getWidth()/2;
		
		//int newleft = centerX - CurrentWidth/2;
		//int newtop = centerY - CurrentHeight/2;
		
		int top = getHeight()/2 - CurrentHeight/2;
		int left = getWidth()/2 - CurrentWidth/2;
		frameDocContainer.layout(left, top, left+CurrentWidth,top+ CurrentHeight);
		
		//frameDocContainer.layout( newleft,newtop,newleft + CurrentWidth,newtop + CurrentHeight);
	}
	
	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev)
	{
		boolean result = super.onInterceptTouchEvent(ev);
	
		
		
		if(ev.getAction() == MotionEvent.ACTION_DOWN)
		{
			mMotionStartX = (int) ev.getX();
			mMotionStartY = (int) ev.getY();
			if(!mJustInterceptedAndIgnored)
			{
				mMostlyScrollingInX = false;
				mMostlyScrollingInY = false;
			}
		}
		else if(ev.getAction()==MotionEvent.ACTION_MOVE)
		{
			detectMostlyScrollingDirection(ev);
		}
		
		if(mMostlyScrollingInY)
		{
			return false;
		}
		if(mMostlyScrollingInX)
		{
			mJustInterceptedAndIgnored = true;
			return true;
		}
		
		return result;
	}

	private void detectMostlyScrollingDirection(MotionEvent ev)
	{
		if(!mMostlyScrollingInX && !mMostlyScrollingInY) //if we dont know which direction we're going yet
		{
			float xDistance = Math.abs(mMotionStartX - ev.getX());
			float yDistance = Math.abs(mMotionStartY - ev.getY());
			
			if(yDistance>xDistance+5)
			{
				mMostlyScrollingInY = true;
			}
			else if(xDistance>yDistance+5)
			{
				mMostlyScrollingInX = true;
			}
		}
	}
	
	private void allowScroll(){
		
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		//canvas.drawColor(Color.WHITE);
		//canvas.drawText(Content, 20, 20, mTextPaint);
		drawTextLines(lines,canvas);
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		// TODO Auto-generated method stub
		final int action = ev.getAction();
		final float x = ev.getX();		
				
		
		switch (action) {
			
		case MotionEvent.ACTION_DOWN:
		
			if (!mScroller.isFinished()) {
				mScroller.abortAnimation();
			}
					
			// Remember where the motion event started
			mLastMotionX = x;
			//mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST : TOUCH_STATE_SCROLLING;
							
			lastX = ev.getX();	
			mMotionStartX = (int) ev.getX();
			mMotionStartY = (int) ev.getY();
			
			break;

		case MotionEvent.ACTION_MOVE:	
			final int xDiff = (int) Math.abs(x - mLastMotionX);
			boolean xMoved = xDiff > mTouchSlop;

			if (xMoved) {
				// Scroll if the user moved far enough along the X axis
				//mTouchState = TOUCH_STATE_SCROLLING;				
			}

			if(mJustInterceptedAndIgnored)
			{				
				dispatchTouchEvent(MotionEvent.obtain(ev.getDownTime(), ev.getEventTime(), MotionEvent.ACTION_DOWN,
						mMotionStartX, mMotionStartY, ev.getPressure(), ev.getSize(), ev.getMetaState(), ev.getXPrecision(), 
						ev.getYPrecision(), ev.getDeviceId(), ev.getEdgeFlags()));
				mJustInterceptedAndIgnored = false;
				
				break;
			}
			int lx = (int)ev.getX();
			int ly = (int)ev.getY();
			int dx = lx - mMotionStartX;
			int dy = ly - mMotionStartY;
			
			//scrollBy((-1)*dx, (-1)*dy);
			
			
			scrollBy(0, (-1)*dy);
			
			mMotionStartX = (int)ev.getX();
			mMotionStartY = (int)ev.getY();
//			
//			int sy = getScrollY();			
//			LogTools.info("ScrollY"+sy);
//			if(sy < 0){
//				scrollTo(0, 0);
//				return true;
//			}
//			
			int sx = getScrollX();
			//int sy = getScrollY();
			
			//LogTools.info("ScrollY"+sy);
			//xDistance = lastX - ev.getX();
			//scrollBy(xDistance, mMotionStartY,0);
//			if (mTouchState == TOUCH_STATE_SCROLLING) {	
//				final int deltaX = (int) (mLastMotionX - x);
//				mLastMotionX = x;
//
//				final int scrollX = getScrollX();			
//				if (deltaX < 0) {
//					if (scrollX > 0) {
//						scrollBy(Math.max(-scrollX, deltaX), 0);
//					}
//				} else if (deltaX > 0) {
//					final int availableToScroll = getChildAt(getChildCount() - 1).getRight() - scrollX - getWidth();
//					
//					if (availableToScroll > 0) {
//						
//						scrollBy(Math.min(availableToScroll, deltaX), 0);
//					}
//				}
//			}
			break;

		case MotionEvent.ACTION_UP:
			int sy = getScrollY();			
		//	LogTools.info("ScrollY"+sy+"docHeight"+DocumentHeight+",containerHeight:"+getHeight());
			int disy = DocumentHeight - sy;
			//LogTools.info("ScrollY"+sy+"docHeight"+DocumentHeight+",containerHeight:"+getHeight()+" ,distance:"+disy);
			
			if(sy < 0){
				scrollTo(0, 0);
				return true;
			}
			
			if(DocumentHeight < getHeight()){
				scrollTo(0, 0);
				return true;
			}
			
			if(disy < getHeight()){
				int by = DocumentHeight - getHeight();
				scrollTo(0, by);
				return true;
			}
			
			break;

		case MotionEvent.ACTION_CANCEL:
			//mTouchState = TOUCH_STATE_REST;
			break;
		}
		
		
		return true;
	}
	
	private void drawTextLines(ArrayList<String> lines,Canvas canvas){
		//canvas.drawText(Content, 20, 20, mTextPaint);
		int lineIndex = 0;
		int startTop = 20;
		int startLeft = 20;
		
		for(String line:lines){
			canvas.drawText(Content, 20, 20, mTextPaint);
			lineIndex++;
		}
	}
	
	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		// TODO Auto-generated method stub
		super.onSizeChanged(w, h, oldw, oldh);
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		// TODO Auto-generated method stub
		LogTools.info("OnMeasure");
		//LogTools.info("height:"+img.getHeight());
		
		int top = getHeight()/2 - CurrentHeight/2;
		int left = getWidth()/2 - CurrentWidth/2;
		
		docContainer.layout(left, top, left+CurrentWidth,top+ CurrentHeight);
		//frameDocContainer.layout(left, top, left+CurrentWidth,top+ CurrentHeight);
		//img.layout(img.posX, img.posY, img.posX+img.Width,img.posY+img.Height);
		//int h = getHeight();
		//DocumentHeight = Math.max(img.getBottom(), DocumentHeight);
		//DocumentWidth = 200;
		
//		if(isFirstLayout){
//			originLeft = getLeft();
//			originWidth = getWidth();
//			isFirstLayout = false;
//		}
		//
	}
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// TODO Auto-generated method stub
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		LogTools.info("OnMeasure");
		final int count = getChildCount();
		for (int i = 0; i < count; i++) {
			getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
		}
		
		//setMeasuredDimension(CurrentWidth, CurrentHeight);

		//LogTools.debug("onmesure of DocumentView widthMeasureSpec:" + widthMeasureSpec + ",heightMeasureSpec:"+heightMeasureSpec);
	}
}
